package stardust.product.platform.webc.spi.servlet;


import java.io.IOException;
import java.io.InputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import stardust.core.io.IOUtils;


@Deprecated
public class DefaultServlet implements Servlet
{

  public static final String SERVLET_INFO = "DefaultServlet";

  private ServletConfig config;

  public void init(ServletConfig config) throws ServletException
  {
    this.config = config;
  }

  public ServletConfig getServletConfig()
  {
    return this.config;
  }

  public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
  {
    HttpServletRequest request;
    HttpServletResponse response;

    if (req instanceof HttpServletRequest && res instanceof HttpServletResponse)
    {
      request = (HttpServletRequest) req;
      response = (HttpServletResponse) res;

      String requestPath = request.getPathInfo();
      InputStream resourceStream = this.config.getServletContext().getResourceAsStream(requestPath);

      if (resourceStream == null)
      {
        response.sendError(404, "资源[" + requestPath + "]未找到。");
      }
      else
      {
        try
        {
          if (requestPath.toLowerCase().endsWith(".jsp") || requestPath.toLowerCase().endsWith(".jspx"))
          {
            RequestDispatcher rd = request.getRequestDispatcher(requestPath);
            rd.forward(request, response);
          }
          else
          {
            IOUtils.readToWrite(resourceStream, response.getOutputStream());
          }
        }
        finally
        {
          resourceStream.close();
        }
      }
    }
  }

  public String getServletInfo()
  {
    return DefaultServlet.SERVLET_INFO;
  }

  public void destroy()
  {
    this.config = null;
  }

}
